﻿using System;
using System.Collections.Generic;
using System.Text;
using DBUtils;
using Motorbike.Model;
using MySql.Data.MySqlClient;
using System.Net;

namespace Motorbike.BLL.Service.IMPL
{
    partial class SystemServiceImpl : ISystemService
    {
        public int GetUserCount()
        {
            using (IDBWrapper wrapper = DBWrapper.OpenWrapper())
            {
                return wrapper.QueryForInt(SqlConstants.QUERY_USER_COUNT);
            }
        }

        public bool SaveUser(User user)
        {
            if (null != user)
            {
                using (IDBWrapper wrapper = DBWrapper.OpenWrapper())
                {
                    return wrapper.Save(user) > 0;
                }
            }
            return false;
        }

        public User GetUser(string userCode)
        {
            if (String.IsNullOrEmpty(userCode))
            {
                return null;
            }
            using (IDBWrapper wrapper = DBWrapper.OpenWrapper())
            {
                List<MySqlParameter> sqlparams = new List<MySqlParameter>();
                sqlparams.Add(new MySqlParameter("@userCode", userCode));
                IList<User> result = wrapper.List<User>(" where code = @userCode", sqlparams.ToArray());
                if (null != result && result.Count > 0)
                {
                    return result[0];
                }
            }
            return null;
        }

        public LoginLog WriteLoginLog(User loginUser)
        {
            if (null == loginUser || String.IsNullOrEmpty(loginUser.Id))
            {
                return null;
            }
            LoginLog loginLog = new LoginLog();
            loginLog.UserId = loginUser.Id;
            IPHostEntry localhost = Dns.GetHostEntry(Dns.GetHostName());
            loginLog.HostName = localhost.HostName;
            loginLog.HostAddress = localhost.AddressList[localhost.AddressList.Length - 1].ToString();
            loginLog.LoginTime = DateTime.Now;

            using (IDBWrapper wrapper = DBWrapper.OpenWrapper())
            {
                wrapper.Save(loginLog);
                return loginLog;
            }
        }

        public void LoginOut(User user, LoginLog loginLog)
        {
            if (null != loginLog)
            {
                using (IDBWrapper wrapper = DBWrapper.OpenWrapper())
                {
                    loginLog.LogoutTime = DateTime.Now;
                    wrapper.Save(loginLog);
                }
            }
        }
    }
}
